package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    //新增菜品，同时保存口味数据
    @Transactional //加注解，记得要去启动类开启
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);

        Long dishId = dishDto.getId();//菜品Id（dish_id）

        //菜品口味    (对stream的任何修改都不会修改背后的数据源,所以后面想要真的修改要给它赋值回去，也即是赋值给flavors)
        List<DishFlavor> flavors = dishDto.getFlavors();
         flavors =  flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList()); //将其转为list集合

        //保存菜品口味到口味表dish_flavor
        dishFlavorService.saveBatch(dishDto.getFlavors());


    }

    //根据id查询dish，dish_flavor
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息，从dish查询
        Dish dish = this.getById(id);

        DishDto dishDto  =new DishDto();
        BeanUtils.copyProperties(dish,dishDto);


        //从菜品查询对应的口味信息，从dish_flavor查询
        LambdaQueryWrapper<DishFlavor> queryWrapper  =new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);


        return dishDto;
    }


    //更新菜品，同时更新对应的口味信息
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {

        //更新dish表基本信息
        this.updateById(dishDto);
        //先删除口味数据，后面在直接增加
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors =  flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList()); //将其转为list集合

        dishFlavorService.saveBatch(flavors);
    }


}
